package com.xmlrpc.service;

import java.io.IOException;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.server.XmlRpcServerConfigImpl;
import org.apache.xmlrpc.webserver.XmlRpcServletServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

public class XmlRpcServerController {
	private XmlRpcServletServer server;
	@Autowired
	private Map<String, IHandler> handlers;
	public Map<String, IHandler> getHandlers() {
		return handlers;
	}

	public void setHandlers(Map<String, IHandler> handlers) {
		this.handlers = handlers;
	}

	@Autowired
	private SpringHandlerMapping handlerMapping;
	public SpringHandlerMapping getHandlerMapping() {
		return handlerMapping;
	}

	public void setHandlerMapping(SpringHandlerMapping handlerMapping) {
		this.handlerMapping = handlerMapping;
	}

	@PostConstruct
	public void init() throws XmlRpcException{
		XmlRpcServerConfigImpl config = new XmlRpcServerConfigImpl();
		server = new XmlRpcServletServer();
		server.setConfig(config); 
		SpringHandlerMapping handlerMapping = new SpringHandlerMapping();
	    handlerMapping.setRequestProcessorFactoryFactory(
	      new SpringRequestProcessorFactory());
	    handlerMapping.setHandlerMapping(handlers);
		server.setHandlerMapping(handlerMapping);
	}
	
	@RequestMapping(value="/1", method=RequestMethod.POST)
	public void serve(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		server.execute(request, response);
	}
}
